package org.ch02.sk.demo05;

import org.ch02.job.test13.SqlGenerate;
import org.ch02.sk.demo04.DruidUtil;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.Map;

/**
 * @author XCH
 * @date 2025 - 03 - 21
 */
public class DbUtil {
    public static Object select4Bean(Class<?> beanClass, Map<String, Object> cond) {
        String sql = SqlGenerate.generateSelect(beanClass, cond);
        Connection conn = DruidUtil.getConnection();
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            pstmt = conn.prepareStatement(sql);
            setParameters(pstmt, cond);
            rs = pstmt.executeQuery();
            if (rs.next()){
                ResultSetMetaData metaData = rs.getMetaData();
                int columnCount = metaData.getColumnCount();
                Object bean = beanClass.getDeclaredConstructor().newInstance();
                for (int i = 1; i <= columnCount; i++) {
                    String columnName = metaData.getColumnName(i);
                    Object value = rs.getObject(columnName);
                    Field field = beanClass.getDeclaredField(columnName);
                    field.setAccessible(true);
                    field.set(bean, value);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    private static void setParameters(PreparedStatement pstmt, Map<String, Object> cond) {
        int index = 1;
        for (Map.Entry<String, Object> entry : cond.entrySet()) {
            Object value = entry.getValue();
            try {
                pstmt.setObject(index++, value);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
